﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using Fleck;
using TuringCup;
using System.IO;
using System.IO.Compression;
namespace GameServer
{
    /// <summary>
    /// 控制播放Replay的类
    /// </summary>
    class GamePlayer
    {
        /// <summary>
        /// 游戏主线程
        /// </summary>
        Thread game;

        /// <summary>
        /// Webscoket 连接
        /// </summary>
        List<IWebSocketConnection> sockets;

        /// <summary>
        /// 游戏状态
        /// </summary>
        GameState gs = new GameState();

        /// <summary>
        /// 上一tick结束时间
        /// </summary>
        int last_tick;

        /// <summary>
        /// replay 路径
        /// </summary>
        private String replay_path = "";

        private StreamReader replay_stream = null;
        private int game_speed = 100;
        public GamePlayer()
        {
        }
        public GamePlayer(List<IWebSocketConnection> sockets, String path,int game_speed = 100)
        {
            this.sockets = sockets;
            replay_path = path;
            this.game_speed = game_speed;
            FileStream fs = new FileStream(path, FileMode.Open);
            GZipStream gzip_stream = new GZipStream(fs, CompressionMode.Decompress);
            replay_stream = new StreamReader(gzip_stream);
        }
        /// <summary>
        /// 开始播放Replay
        /// </summary>
        public void Start()
        {
            game = new Thread(game_run);
        }
        /// <summary>
        /// 恢复播放Replay
        /// </summary>
        public void Continue()
        {
            last_tick = Environment.TickCount;
            game.Start();
        }
        /// <summary>
        /// 停止播放Replay
        /// </summary>
        public void Stop()
        {
            if (game != null)
                game.Abort();
            if (replay_stream != null)
                replay_stream.Close();
        }

        /// <summary>
        /// 游戏逻辑主循环
        /// </summary>
        void game_run()
        {
            int t = 0;
            while (!replay_stream.EndOfStream)//主循环
            {
                //gs = GameState.Load(replay_stream.ReadLine());
                string gss = replay_stream.ReadLine();
                foreach (var socket in sockets.ToList())
                {
                    socket.Send(gss);
                }
                int now = Environment.TickCount;
                last_tick += game_speed;
                Console.WriteLine(t++);
                Thread.Sleep(Math.Max(0, last_tick - now));
            }
        }

    }
}
